package com.jfirer.validator.descriptor;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.validation.ConstraintValidatorFactory;
import javax.validation.metadata.BeanDescriptor;
import com.jfirer.validator.ExecutableDescriptorFactory;

public class BeanDescriptorFactory
{
	private Map<Class<?>, BeanDescriptor> store	= new ConcurrentHashMap<Class<?>, BeanDescriptor>();
	private ExecutableDescriptorFactory   executableDescriptorFactory;
	private ConstraintValidatorFactory    constraintValidatorFactory;
	
	public BeanDescriptorFactory(ExecutableDescriptorFactory executableDescriptorFactory, ConstraintValidatorFactory constraintValidatorFactory)
	{
		this.executableDescriptorFactory = executableDescriptorFactory;
		this.constraintValidatorFactory = constraintValidatorFactory;
	}
	
	public BeanDescriptor getInstance(Class<?> clazz)
	{
		BeanDescriptor beanDescriptor = store.get(clazz);
		if (beanDescriptor == null)
		{
			synchronized (clazz)
			{
				beanDescriptor = store.get(clazz);
				if (beanDescriptor == null)
				{
					beanDescriptor = new BeanDescriptorImpl(clazz, executableDescriptorFactory, constraintValidatorFactory);
					store.put(clazz, beanDescriptor);
				}
			}
		}
		return beanDescriptor;
	}
}
